﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using carShop.Data.EntityFramework;
using carShop.Data.Repositories;
using carShop.Data.Repositories.Custom;
using carShop.Models;

namespace carShop.Data
{
    public class UnitOfWork:IUnitOfWork,IDisposable
    {
        private CarShopDbContext dbContext = new CarShopDbContext();
        private CarRepository carRepository;
        private UserRepository userRepository;
        private Repository<Image> imageRepository;
    
        public CarRepository CarRepository
        {
            get
            
            {
                if (carRepository == null)
                    return carRepository = new CarRepository(dbContext);
                
                return carRepository;
            }
            
        }

        public UserRepository UserRepository
        {
            get
            {
                if (carRepository == null)
                    return userRepository = new UserRepository(dbContext);
                
                return userRepository;
            }

        }

        public Repository<Image> ImageRepository
        {
            get
            {
                if (imageRepository == null)
                    return imageRepository = new Repository<Image>(dbContext);

                return imageRepository;
            }

        }

        public UnitOfWork()
        {
            //disable these to avoid problems
            dbContext.Configuration.ProxyCreationEnabled = false;
            dbContext.Configuration.LazyLoadingEnabled = false;
            dbContext.Configuration.ValidateOnSaveEnabled = false;

        }

        public void Commit()
        {
            dbContext.SaveChanges();
        }

        public void Rollback()
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            dbContext.Dispose();
        }
    }
}